import { useCookie } from '#app';

export const useAuth = () => {
  const user = ref(null);
  const loading = ref(false);
  const isAuthenticated = computed(() => !!user.value);

  const loadUserFromSession = () => {
    const session = useCookie('session');
    if (session.value) {
      try {
        const parsed = JSON.parse(session.value);
        user.value = parsed;
      } catch (e) {
        console.error('Failed to parse session cookie:', e);
        user.value = null;
      }
    } else {
      user.value = null;
    }
  };

  const fetchUserInfo = async () => {
    loading.value = true;
    try {
      const res = await fetch('/api/auth/me', {
        credentials: 'include'
      });
      if (!res.ok) {
        user.value = null;
        return;
      }
      const data = await res.json();
      if (data?.authenticated && data?.user) {
        user.value = data.user;
      } else {
        user.value = null;
      }
    } catch (error) {
      console.error('Failed to fetch auth info:', error);
      user.value = null;
    } finally {
      loading.value = false;
    }
  };

  const initAuth = async () => {
    loadUserFromSession();
    if (!user.value) {
      await fetchUserInfo();
    }
  };

  onMounted(() => {
    initAuth();
  });

  watch(
    () => useCookie('session').value,
    () => {
      loadUserFromSession();
      if (!user.value) {
        fetchUserInfo();
      }
    }
  );

  const refreshAuth = async () => {
    await fetchUserInfo();
  };

  const logout = async () => {
    const cookie = useCookie('session');
    cookie.value = null;
    user.value = null;
    await navigateTo('/login');
  };

  return {
    user,
    isAuthenticated,
    loading,
    initAuth,
    refreshAuth,
    logout
  };
};

// This makes the composable auto-importable
export default useAuth;
